﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Gem_Tools;
using Gem_Tools_Entity.Gem_Tools;
using Gem_Tools_Controller.Gem_Tools;
using Gem_Tools_Utility;

namespace GE_Management_Tool
{
    public partial class frmLogin : frmBase
    {
        CStaff m_staff;

        public frmLogin()
        {
            InitializeComponent();
        }

        private string Check_Error()
        {
            StringBuilder v_sb = new StringBuilder();
            if (txtUserName.Text == "")
            {
                v_sb.AppendLine("-Missing User Name.");
            }
            if (txtPassword.Text == "")
            {
                v_sb.AppendLine("-Missing Password.");
            }

            return v_sb.ToString();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            string error = Check_Error();

            try
            {
                if (error != "")
                {
                    throw new Exception(error);
                }
                string v_strUsername = txtUserName.Text;
                string v_strPassword = CUtility.MD5_Encrypt(txtPassword.Text);
                Login(v_strUsername, v_strPassword);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                Application.Exit();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void Login(string username, string password)
        {
            CStaff_Controller v_objCtrlStaff = new CStaff_Controller();
            m_staff = v_objCtrlStaff.F0_Login(username, password);
            if (m_staff != null)
            {
                CSession.Active_User_Name = m_staff.UserName;
                CSession.Active_Staff = m_staff;
                this.Close();
            }
            else
            {
                throw new Exception("Invalid Username or Password, Try again or contact Admin.");
            }
        }

        private void frmLogin_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnLogin_Click(null, null);
            }
        }

        private void frmLogin_Load(object sender, EventArgs e)
        {
            //btnLogin_Click(null, null);
        }
    }
}